<template>
   <div class="select-dump" :class="{'has-field': hasField}">
      <div class="form-item">
         <span class="form-item-tit" v-if="isShowTitle">所属分层：</span>
         <el-select v-model="ruleForm.Tree1" placeholder="请选择" @change="selectChang1">
            <el-option
               v-for="item in treeList"
            :key="item.id"
            :label="item.dirName"
            :value="item.id"
            >
            </el-option>
         </el-select>
         <el-select v-model="ruleForm.Tree2" placeholder="请选择" @change="selectChang2"  v-show="selectTree2.length">
            <el-option v-for="item in selectTree2" 
            :key="item.id"
            :label="item.dirName"
            :value="item.id"></el-option>
         </el-select>
         <el-select v-model="ruleForm.Tree3" placeholder="请选择" @change="selectChang3"  v-show="selectTree3.length">
            <el-option v-for="item in selectTree3" 
            :key="item.id"
            :label="item.dirName"
            :value="item.id"></el-option>
         </el-select>
         <el-select v-model="ruleForm.Tree4" placeholder="请选择"  @change="selectChang4"  v-show="selectTree4.length">
            <el-option v-for="item in selectTree4" 
            :key="item.id"
            :label="item.dirName"
            :value="item.id" ></el-option>
         </el-select>
         <el-select v-model="ruleForm.Tree5" placeholder="请选择"  @change="selectChang5"  v-show="selectTree5.length">
            <el-option v-for="item in selectTree5" 
            :key="item.id"
            :label="item.dirName"
            :value="item.id"></el-option>
         </el-select>
         <el-autocomplete
            v-model="dirName"
            v-show="baseList.length>0 && isTable"
            class="associa-select"
            :class="{'has-field' : hasField && fieldList.length}"
            :fetch-suggestions="querySearchAsync"
            :popper-append-to-body="!hasField"
            placeholder="请输入表名称"
            clearable
            @clear="handleClearTable"
            @select="handleSelectTable"
         >
         </el-autocomplete>
         <el-select v-model="ruleForm.field" placeholder="请选择"  @change="selectChangeField" v-show="hasField && fieldList.length" multiple collapse-tags>
            <el-checkbox v-model="checked" @change="onSelectAllCheckbox">全选</el-checkbox>
            <el-option v-for="item in fieldList" 
            :key="item.id"
            :label="item.fieldName"
            :value="item.id" ></el-option>
         </el-select>
         <el-button size="mini" class="search-btn-item" @click="searchHandle" v-show="isShowBtn" type="primary"> 查询</el-button>
      </div>
   </div>
</template>
<script>
import { mapTreeItem } from '@/api/dataManagement/system/dir';
import { getDatabeseList, getFieldsList } from '@/api/dataManagement/system/info';

export default {
   name:'select-dump',
   props: {
      // 是否显示标题
      isShowTitle: {
         type: Boolean,
         default: true,
      },
      // 是否显示搜索按钮
      isShowBtn: {
         type: Boolean,
         default: true,
      },
      // 是否显示表
      isTable: {
         type: Boolean,
         default: false,
      },
      // 是否展示表字段
      hasField: {
         type: Boolean,
         default: false,
      },
      data: {
         type: Object,
         default: () => {
            return {}
         },
      },
      // 是否过滤器树没有权限的节点
      filterPermission: {
         type: Boolean,
         default: false,
      }
   },
   data(){
      return {
         ruleForm:{
            Tree1:'',
            Tree2:'',
            Tree3:'',
            Tree4:'',
            Tree5:'',
            Tree6:'',
            table: '',
            field: []
         },
         tableId:'',
         baseList:[],
         dirName:'',
         dirId:'',
         treeList:[],
         selectTree1:[],
         selectTree2:[],
         selectTree3:[],
         selectTree4:[],
         selectTree5:[],
         selectTree6:[],
         fieldList:[],
         isChangeOrignal: false,
         checked: false
      }
   },
   mounted(){
      this.getTreeList()
   },
   computed: {
      originalData: {
         get() {
            return this.data
         },
         set(newValue) {
            
         }
      }
   },
   methods:{
      selectChang1(value,isTrue){
         // this.ruleForm={
         //    Tree2:'',
         //    Tree3:'',
         //    Tree4:'',
         //    Tree5:'',
         // },
         this.ruleForm.Tree2= ''
         this.selectTree2 = [];
         this.selectTree3 = [];
         this.selectTree4 = [];
         this.selectTree5 = [];
         this.selectTree6 = [];
         this.baseList = []
         this.ruleForm.table = ''
         this.fieldList = []
         this.ruleForm.field = []
         this.isChangeOrignal = true
         for(var i=0;i<this.treeList.length;i++){
            if(this.treeList[i].id == value){
               this.ruleForm.Tree1 = this.treeList[i].dirName
               this.dirId = this.treeList[i].id;
               // this.handleSelectTable({dirName:this.treeList[i].dirName})
               if(isTrue) {
                  this.selectTree2 = []
               }else {
                  this.selectTree2 = this.treeList[i].children
               }
               
            }
         }
         this.prefix = '';
      },
      selectChang2(value,isTrue){
         this.selectTree3 = [];
         this.ruleForm.Tree3= ''
         this.baseList = []
         this.ruleForm.table = ''
         this.fieldList = []
         this.ruleForm.field = []
         this.isChangeOrignal = true
         // this.ruleForm={
         //    Tree3:'',
         //    Tree4:'',
         //    Tree5:'',
         // }
         for(var i=0;i<this.selectTree2.length;i++){
            if(this.selectTree2[i].children.length != 0 && this.selectTree2[i].id ==value) {
               this.selectTree3 = this.selectTree2[i].children
               this.ruleForm.Tree2 = this.selectTree2[i].dirName
                this.dirId = this.selectTree2[i].id;
            }
            if(this.selectTree2[i].children.length == 0 && this.selectTree2[i].id ==value){
               this.prefix =this.selectTree2[i].prefix
               this.dirId = this.selectTree2[i].id;
               this.ruleForm.Tree2 = this.selectTree2[i].dirName
               // this.handleSelectTable({dirName:this.selectTree2[i].dirName})
               if(this.isTable){
                  this.DatabeseList();
               }
            }
         }
      },
      selectChang3(value,isTrue){
         // this.ruleForm={
         //    Tree4:'',
         //    Tree5:'',
         // }
         this.ruleForm.Tree4= ''
         this.selectTree4 = [];
         this.baseList = []
         this.ruleForm.table = ''
         this.fieldList = []
         this.ruleForm.field = []
         this.isChangeOrignal = true
         for(var i=0;i<this.selectTree3.length;i++){
            if(this.selectTree3[i].children.length != 0 && this.selectTree3[i].id ==value) {
               this.selectTree4 = this.selectTree3[i].children
               this.ruleForm.Tree3 = this.selectTree3[i].dirName
               this.dirId = this.selectTree3[i].id;
            }
            if(this.selectTree3[i].children.length == 0 && this.selectTree3[i].id ==value){
               this.prefix =this.selectTree3[i].prefix;
               this.dirId = this.selectTree3[i].id;
               this.ruleForm.Tree3 = this.selectTree3[i].dirName
               // this.handleSelectTable({dirName:this.selectTree3[i].dirName})
               if(this.isTable){
                  this.DatabeseList();
               }
            }
         }
      },
      selectChang4(value,isTrue){
         // this.ruleForm={
         //    Tree5:'',
         // }
         this.ruleForm.Tree5= ''
         this.selectTree5 = [];
         this.baseList = []
         this.ruleForm.table = ''
         this.fieldList = []
         this.ruleForm.field = []
         this.isChangeOrignal = true
         for(var i=0;i<this.selectTree4.length;i++){
            if(this.selectTree4[i].children.length != 0 && this.selectTree4[i].id ==value) {
               this.selectTree5 = this.selectTree4[i].children
               this.dirId = this.selectTree4[i].id;
               this.ruleForm.Tree4 = this.selectTree4[i].dirName
            } 
            if(this.selectTree4[i].children.length == 0 && this.selectTree4[i].id ==value){
               this.prefix =this.selectTree4[i].prefix;
               this.dirId = this.selectTree4[i].id;
               this.ruleForm.Tree4 = this.selectTree4[i].dirName
               // this.handleSelectTable({dirName:this.selectTree4[i].dirName})
               if(this.isTable){
                  this.DatabeseList();
               }
            }
         }
      },
      selectChang5(value,isTrue){
         for(var i=0;i<this.selectTree5.length;i++){
            if(this.selectTree5[i].children.length != 0 && this.selectTree5[i].id ==value) {
               this.selectTree6 = this.selectTree5[i].children
                 this.dirId = this.selectTree5[i].id
               if(isTrue) {
                  this.from2.Tree5 = this.selectTree5[i].dirName
               }
            }
            if(this.selectTree5[i].children.length == 0 && this.selectTree5[i].id ==value){
               this.prefix =this.selectTree5[i].prefix
               this.dirId = this.selectTree5[i].id
               if(isTrue) {
                  this.from2.Tree5 = this.selectTree5[i].dirName
               }
               // this.handleSelect({dirName:this.selectTree5[i].dirName})
               if(this.isTable){
                  this.DatabeseList();
               }
            }
         }
      },
      selectChangeField(values){
         if (values.length === this.fieldList.length) {
            this.checked = true
         } else {
            this.checked = false
         }

         let fields = this.fieldList.filter(field => {
            let index = values.findIndex(id => {
               return id == field.id
            })
            return index !== -1
         })

         var obj = {
            dirId: this.dirId,
            data: this.ruleForm,
            fields
         }
         this.$emit('search',obj)
      },
      onSelectAllCheckbox() {
         this.ruleForm.field = []
         if (this.checked) {
            this.fieldList.map((item) => {
               this.ruleForm.field.push(item.id)
            })
         } else {
            this.ruleForm.field = []
         }

         let fields = this.fieldList.filter(field => {
            let index = this.ruleForm.field.findIndex(id => {
               return id == field.id
            })
            return index !== -1
         })

         var obj = {
            dirId: this.dirId,
            data: this.ruleForm,
            fields
         }
         this.$emit('search',obj)
      },
      DatabeseList(){
			this.baseList = []
			this.dirName =''
			getDatabeseList({dirId:this.dirId}).then(res=>{
				var list = []
				if(res.rows.length>0) {
					for(var i=0;i<res.rows.length;i++){
                  var obj = {}
                  obj.value=res.rows[i].tableName
                  obj.id=res.rows[i].id
                  list.push(obj)
               }
               this.baseList = list

               // 数据回填处理
               if (!this.isChangeOrignal && this.originalData.table && this.originalData.table.length) {
                  let table = JSON.parse(this.originalData.table)
                  this.dirName = table[0].tableName
                  this.ruleForm.table = {
                     id: table[0].id,
                     value: table[0].tableName,
                  }
                  this.getTableField(table[0].id)
               }
				}
			})
		},
      querySearchAsync(queryString, cb) {
        var restaurants = this.baseList;
        var results = queryString ? restaurants.filter(this.createStateFilter(queryString)) : restaurants;
          cb(results);
      },
      createStateFilter(queryString) {
        return (state) => {
          return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
        };
      },
      empty(val){
         if(typeof(val) != 'boolean') {
            return false;
         }
         if(val){
            this.selectTree1=[];
            this.selectTree2=[];
            this.selectTree3=[];
            this.selectTree4=[];
            this.selectTree5=[];
            this.selectTree6=[];
            this.fieldList=[];
            this.dirName ='';
            this.baseList= [];
            this.ruleForm={
               Tree1:'',
               Tree2:'',
               Tree3:'',
               Tree4:'',
               Tree5:'',
               Tree6:'',
               table: '',
               field:[],
            }
         }
      },
      handleClearTable() {
         this.fieldList = []
         this.ruleForm.field = []
      },
      handleSelectTable(item){
         if (this.isTable) {
            // 最后一级显示表字段
            if (this.hasField) {
               this.handleClearTable()
               this.ruleForm.table = item
               this.getTableField(item.id)
            } else {
               var obj = {
                  dirId:this.dirId,
                  item,
               }
               this.$emit('search',obj)
               return false;
            }
            
         } else {
            var obj = {
               dirId:this.dirId,
               item,
            }
            this.$emit('search',obj)
         }
      },
      getTableField(tableId) {
         if (!tableId) return;

         getFieldsList({ params: { tableId } }).then(res => {
            this.fieldList = res.data

            // 数据回填处理
            if (!this.isChangeOrignal && this.originalData.fields && this.originalData.fields.length) {
               let fields = JSON.parse(this.originalData.fields)
               this.ruleForm.field = fields.map(item => Number(item.id))
            }
         }).catch(() => {
            this.fieldList = []
         })
      },
      getTreeList(){
         let params = {}
         if (this.filterPermission) {
            params.filter = true
         }
         mapTreeItem(params).then(res=>{
            this.treeList = res.data.children

            // 数据回填处理
            if (this.originalData.dataSourceList && this.originalData.dataSourceList.length) {
               let ids = this.originalData.dataSourceList.reverse()
               for (let i = 0; i < ids.length; i++) {
                  const id = ids[i].did;
                  if (i == 0) this.formatBackFillData(id, 'Tree1', this.treeList, 'selectTree2')
                  if (i == 1) this.formatBackFillData(id, 'Tree2', this.selectTree2, 'selectTree3')
                  if (i == 2) this.formatBackFillData(id, 'Tree3', this.selectTree3, 'selectTree4')
                  if (i == 3) this.formatBackFillData(id, 'Tree4', this.selectTree4, 'selectTree5')
                  if (i == 4) this.formatBackFillData(id, 'Tree5', this.selectTree5, 'selectTree6')
               }
            }
         })
      },
      formatBackFillData(id, currentData, treeList, nextTreeList) {
         let obj = treeList.find(item => {
            return item.id == id
         })

         if (obj) {
            this.dirId = id
            this.ruleForm[currentData] = obj.dirName
            if (obj.children.length) {
               this[nextTreeList] = obj.children
            } else {
               this.DatabeseList()
            }
         }
      },
      searchHandle(){
         this.handleSelectTable({dirName:''})
      },
      selectBase(arr,isTrue){
         for(var i=0;i<arr.length;i++){
            this['selectChang'+(i+1)](arr[i],isTrue)
         }
      },
   }
}
</script>

<style lang="scss" scoped>
.select-dump:not(.has-field)::v-deep{
   overflow: hidden;
   color:#606266;
   font-size:16px;
   margin-bottom:20px;
}
.search-btn-item::v-deep.el-button--mini{
   height:32px;
}
.form-item{
   margin-right:19px;
   display: flex;
   align-items: center;

   .form-item-tit{
      min-width:80px;
   }
   span{
      float:left;
      height:34px;
      line-height:34px;
      font-size:14px
   }
   .el-input,.el-select{
      width:276px;
      float:left;
      margin-right:10px;
   }
   .database-name.el-input{
      width:151px;
   }
   .form-name.el-input{
      width:320px;
   }
   .el-autocomplete.has-field {
      margin-right:10px;
   }
   ::v-deep .el-autocomplete-suggestion{
      width: auto!important;
   }
}

.el-checkbox {
   width: 100%;
   height: 34px;
   line-height: 34px;
   padding: 0 20px;
   text-align: right;
}
</style>